package com.bauer.base.concurrent.quene;

import com.bauer.base.bean.User;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

/**
 * @Author ：rui.wei
 * @Date ：Created in 15:19 2019/4/23
 * @Description：
 */
public class BlockQueneDemo {


    static class Provider implements Runnable {

        private BlockingQueue<User> queue;

        public Provider(BlockingQueue<User> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                System.out.println("before user1");
                queue.put(new User("user1"));
                System.out.println("+");
                queue.put(new User("user2"));
                System.out.println("user2");
                queue.put(new User("user3"));
                System.out.println("user3");
                queue.put(new User("user4"));
                System.out.println("user4");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    static class Consumer implements Runnable {

        private BlockingQueue<User> queue;

        public Consumer(BlockingQueue<User> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                User user = queue.take();
                System.out.println(user.getUserName());

                user = queue.take();
                System.out.println(user.getUserName());

                user = queue.take();
                System.out.println(user.getUserName());

                user = queue.take();
                System.out.println(user.getUserName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void arrayBlockingQueue(){
        BlockingQueue<User> blockingQueue = new ArrayBlockingQueue<>(3);

        new Thread(new Provider(blockingQueue)).start();
        new Thread(new Consumer(blockingQueue)).start();
    }

    private  static BlockingQueue<User> synchronousQueue(){
        BlockingQueue<User> blockingQueue = new SynchronousQueue<>();
        new Thread(new Provider(blockingQueue)).start();

        return blockingQueue;
    }


    public static void main(String[] args) {
        try {
            synchronousQueue();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
